/* Team 2
   CS513
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netinet/in.h>
#include <netdb.h>

const char *PORT="7766"; // unused port

int main(int argc, char **argv){
	// Check CL arguments for proper amount of items and string length
	char serverAddress[32];
	if(argc>2){
		fprintf(stderr,"Usage: ./client [server]\n");
	}
	else if(argc==1){
		strcpy(serverAddress,"127.0.0.1\0");
	}

	int status; // return status for getaddrinfo
	struct addrinfo hints;
	struct addrinfo *servinfo;  // for info stored by getaddrinfo()
	memset(&hints, 0, sizeof hints); // make sure data is initialized to 0
	hints.ai_family = AF_INET;     // we are using IPv4
	hints.ai_socktype = SOCK_STREAM; // TCP stream sockets (not UDP)

	// retrieve information for connecting 
	status = getaddrinfo(argv[1], PORT, &hints, &servinfo);
	if(status!=0){
		fprintf(stderr, "Error with getaddrinfo: %s\n", gai_strerror(status));
		exit(1);
	}

	// create socket to connect through
	int sock=socket(servinfo->ai_family,servinfo->ai_socktype,servinfo->ai_protocol);
	if(sock<=0){
		fprintf(stderr,"Error creating socket\n");
		exit(1);
	}

	// connect to server
	if(connect(sock,servinfo->ai_addr,servinfo->ai_addrlen)==-1){
		close(sock);
		perror("Error connecting to server");
		exit(1);
	}

	// Start with first message in argv and go through all remaining
	while(1){
		// send DLE EXT
		char send_buf[2];
		send_buf[0]=(char)0x10; //hex for DLE
		send_buf[1]=(char)0x03; //hex for ETX

		// ensure we received the correct information back from server
		/*
		   if(recv_buf[0]==(char)0x10 && recv_buf[1]==(char)0x03){
		   printf("Done\n");
		   }
		   else{
		   fprintf(stderr,"Error: expected DLE ETX from server\n");
		   close(sock); // close communicating socket
		   exit(1);
		   }
		 */
	}
	close(sock); // close communicating socket
	return 0;
}

